<?php namespace App\Http\Controllers\Admin;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Item;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;

class ItemController extends Controller
{
//显示内容
    public function getIndex(Request $request, $key)
    {
        $items = Item::where('type', $key);
        $appends = $request->all();
        $items = $items->paginate(config('site.admin.pageSize'));
        return view('admin.item.index', [
            'items' => $items,
            'appends' => $appends,
            'type' => $key
        ]);
    }

    public function getUpdate($type = 'news', $id = 0)
    {
        $model = Item::findOrNew($id);
        if(("" == $model || $model->type != $type) && $id != 0){
            abort('404');
        }
        $data = $model->content;
        $data = json_decode($data,true);
        //dd($data);
        return view('admin.item.update', ['model' => $model,'data'=>$data, 'type' => $type]);
    }


//提交获取的数据
    public function postUpdate(Request $request, $type, $id = 0)
    {
        $model = Item::findOrNew($id);
        $data = $request->all();
        unset($data['_token']);

        if (!$model->id) {
            $model->user_id = \Auth::user()->id;
        }
        if (Cache::has('validator')) {
            $validator = Cache::get('validator');
        } else {
            $validator = [];
        }
        if (!isset($validator[$type])) {
            $tmparry = config('site.items.' . $type);
            $validator[$type]['attributes'] = [];
            $validator[$type]['rules'] = [];
            foreach($tmparry['data'] as $key=>$item){
                if("" != $item['attribute']){
                    $validator[$type]['attributes'][$key]=$item['name'];
                    $validator[$type]['rules'][$key]=$item['attribute'];
                }
            }
            unset($key,$item);
            Cache::put('validator',$validator,config('site.cacheTime'));
        }
        $validators = $validator[$type];
        unset($validator);
        $validator = \Validator::make($data, $validators['rules'], Config::get('site.message'), $validators['attributes']);
        if ($validator->fails()) {
            $message = $validator->messages();
            $ret['message'] = $message;
            $ret['state'] = 'fail';
            foreach ($validators['attributes'] as $k => $attr) {
                if ($message->has($k)) {
                    $ret['message'] = $message->first($k);
                    break;
                }
            }
        } else {
            $datas['description'] = "暂无简介";
            if (isset($data['description']) && trim($data['description']) == ''&& '' != $data['content']) { //自动截取内容作为描述
                $datas['description'] = $data['description'] = mb_strcut(str_replace(array("\r\n", "\t", '[page]', '[/page]', '&ldquo;', '&rdquo;', '&nbsp;'), '', strip_tags($data['content'])), 0, 400, 'utf-8');
            }
            $datas['name'] = reset($data);
            $datas['kind'] = isset($data['types']) ? $data['types'] : 0;
            $datas['type'] = $type;
            $datas['content'] = json_encode($data);
            if (!$model->id) {
                $model->user_id = \Auth::user()->id;
            }
            $model->fill($datas);
            $model->save();//写入数据库

            if ($model->id) {
                $ret = ['state' => 'success', 'message' => '操作成功'];
            } else {
                $ret['message'] = '保存出错';
            }
        }
        if(1 == config('site.items.' . $type.'.nav')){
            //组装导航栏
            if(Cache::has('nav')){
                $nav = Cache::get('nav');
                Cache::forget('nav');
                $nav[$type]['data'] = Item::where('type',$type)->select('id','name')->get();
                Cache::forever('nav',$nav);
            }else{
                foreach(config('site.items') as $key=>$item){
                    $nav[$key]['name'] = $item['name'];
                    $nav[$key]['data'] = [];
                }
                $nav[$type]['data'] = Item::where('type',$type)->select('id','name')->get();
                Cache::forever('nav',$nav);
            }
        }
        return \Response::json($ret);
    }

    public function postDelete($id,$type)
    {
        $ret = ['state' => 'fail', 'message' => '未知错误，请刷新重试'];
        $chlid = config('site.items.'.$type);
        if(isset($chlid['child'])){
            $chlid = $chlid['child'];
            $item = Item::where('type',$chlid)->where('kind',$id)->first();
            if(null == $item){
                if (Item::destroy($id)) {
                    $ret = ['state' => 'success', 'message' => '删除成功'];
                    Cache::forget('nav');
                }
            } else {
                $ret = ['state' => 'fail', 'message' => '该类别中，仍然包含对应的项目，请修改后重试'];
            }
        }else{
            if (Item::destroy($id)) {
                $ret = ['state' => 'success', 'message' => '删除成功'];
                Cache::forget('nav');
            }
        }
        return \Response::json($ret);
    }
}
